package my.office.see;

import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.util.List;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

/**
 * 利用openoffice转换office文档
 *  soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard 
 * @author guojian
 *
 */
public class OpenOfficeConvert {
	private static final String OPENOFFICE_HOME = "C:/Program Files (x86)/OpenOffice 4/program/";

	private static final String START_OPENOFFICE_COMMAND = "soffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp\" ";

	private static final OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);

	private static final OpenOfficeConvert oc = new OpenOfficeConvert();

	private void startOpenofficeService() {
		try {
			Runtime.getRuntime().exec(OPENOFFICE_HOME + START_OPENOFFICE_COMMAND);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private OpenOfficeConnection getConnectedOpenOfficeConnection() {
		try {
			connection.connect();
		} catch (ConnectException e) {
			startOpenofficeService();
			try {
				connection.connect();
			} catch (ConnectException e1) {
				e1.printStackTrace();
			}
		}
		return connection;
	}

	public static void office2Pdf(File in) {
		DocumentConverter converter = new OpenOfficeDocumentConverter(oc.getConnectedOpenOfficeConnection());
		try {
			converter.convert(in, new File(getOutFilePath(in)));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			connection.disconnect();
		}
	}

	public static void officeList2Pdf(List<File> fileInList) {
		DocumentConverter converter = new OpenOfficeDocumentConverter(oc.getConnectedOpenOfficeConnection());
		for (File file : fileInList) {
			String outFilePath = getOutFilePath(file);
			converter.convert(file, new File(outFilePath));
		}
		connection.disconnect();
	}

	private static String getOutFilePath(File file) {
		String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
		String infilePath = file.getAbsolutePath();
		return infilePath.replaceAll(suffix, "pdf");
	}

	public static void main(String[] args) {
		
		File filein3 = new File("g:/光明新区金融突发事件应急预案简本.doc");
		OpenOfficeConvert.office2Pdf(filein3);
		

	}
}
